<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      padding: 100px;
    }
    #box {
      position: relative;
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }
    #box>img {
      width: 100%;
    }
    #mask {
      display: none;
      position: absolute;
      cursor: move;
      left: 0;
      top: 0;
      width: 200px;
      height: 200px;
      background-color: rgba(255,0,0,0.2);
    }

    #bigBox {
      display: none;
      position: absolute;
      overflow: hidden;
      left: 310px;
      top: 0;
      width: 450px;
      height: 450px;
      border: 2px solid red;
    }
    #bigBox > img{
      position: absolute;
      width: 600px;
      height: 600px;
    }
  </style>
</head>
<body>
  <div id="box">
    <img id="img" src="https://img14.360buyimg.com/n1/jfs/t1/202322/28/3450/115358/6129a36cE0ebaf894/0e0362cba1102838.jpg" alt="">
    <div id="mask"></div>
    <div id="bigBox">
      <img id="bigImg" src="https://img14.360buyimg.com/n1/jfs/t1/202322/28/3450/115358/6129a36cE0ebaf894/0e0362cba1102838.jpg" alt="">
    </div>
  </div>

  <script>
    var box = document.querySelector('#box')
    var img = document.querySelector('#img')
    var mask = document.querySelector('#mask')
    var bigBox = document.querySelector('#bigBox')
    var bigImg = document.querySelector('#bigImg')

    // 进入
    box.onmouseenter = function() {
      mask.style.display = 'block'
      bigBox.style.display = 'block'
    }    

    // 离开
    box.onmouseleave = function() {
      mask.style.display = 'none'
      bigBox.style.display = 'none'
    }

    box.onmousemove = function(e) {
      var x = e.pageX - box.offsetLeft - mask.offsetWidth / 2
      var y = e.pageY - box.offsetTop - mask.offsetHeight / 2

      var maskX = box.offsetWidth - mask.offsetWidth
      var maskY = box.offsetHeight - mask.offsetHeight

      if(x <= 0) {
        x = 0
      } else if(x >= maskX) {
        x = maskX
      }
      
      if(y <= 0) {
        y = 0
      } else if(y >= maskY) {
        y = maskY
      }

      mask.style.left = x + 'px'
      mask.style.top = y + 'px'

      // 蔗罩移动的距离 / 遮照可以移动的距离 = 图片移动的距离 / 图片可以移动的距离

      var imgX = bigImg.offsetWidth - bigBox.offsetWidth
      var imgMoveX = x / maskX * imgX

      var imgY = bigImg.offsetHeight - bigBox.offsetHeight
      var imgMoveY = y / maskY * imgY

      bigImg.style.left = -imgMoveX + 'px'
      bigImg.style.top = -imgMoveY + 'px'
    }
  </script>
</body>
</html>